package br.ita.comp.ces22.quiz.core.dao.jpa;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import br.ita.comp.ces22.quiz.core.dao.QuizDAO;
import br.ita.comp.ces22.quiz.domain.Question;
import br.ita.comp.ces22.quiz.domain.Quiz;
import br.ita.comp.ces22.quiz.domain.QuizKey;
import br.ita.comp.ces22.quiz.domain.User;

public class QuizJPADAO extends QuizDAO{
	
	private EntityManager em;
	
	public QuizJPADAO(){
		EntityManagerFactory emf = Persistence.createEntityManagerFactory("mysql");
		em = emf.createEntityManager();
	}
	
	public Quiz getById(Object oQuizKey){
		QuizKey quizkey = (QuizKey) oQuizKey;
		Quiz quiz = 
		(Quiz) em.createNamedQuery("Quiz.findById").setParameter("idQuestion", quizkey.getIdQuestion()).setParameter("login", quizkey.getLogin()).getSingleResult();
		return quiz;
	}
	public void insert(Quiz quiz){
		em.getTransaction().begin();
		em.persist(quiz);
		em.getTransaction().commit();
	}
	public List<Question> getRandomQuestions(User user){
		List<Quiz> listafeitos = 
		em.createNamedQuery("Quiz.findById").setParameter("login", user.getLogin()).getResultList();
		
		Integer qtquestions = 
		em.createNativeQuery("Question.findAll").getResultList().size();
		
		
		ArrayList<Integer> idfeitos = new ArrayList<Integer>();
		
		for(int i=0;i<listafeitos.size();i++){
			Integer aux=0;
			aux = listafeitos.get(i).getQk().getIdQuestion();
			idfeitos.add(aux);
		}
		 
		ArrayList<Question> randomList = new ArrayList<Question>();
		for(int i=0;i<5;i++){
			int aux =(int) Math.random()*qtquestions;
			if(!idfeitos.contains(aux)){
				randomList.add(
				(Question)em.createNamedQuery("Question.findById").setParameter("idQuestion",aux).getSingleResult());				
			}
		}
		return randomList;
	}
	
}
